package baseFx.serialization.json.jackson;

import baseFx.serialization.json.LongFormat;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.BeanProperty;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.JsonDeserializer;
import com.fasterxml.jackson.databind.deser.ContextualDeserializer;

import java.io.IOException;
import java.math.BigDecimal;

public class LongDeserializer extends JsonDeserializer<Long> implements ContextualDeserializer {
    private LongFormat fmt;

    @Override
    public Long deserialize(JsonParser jsonParser, DeserializationContext deserializationContext) throws IOException {
        if (fmt == null) {
            return jsonParser.getValueAsLong();
        }
        String num = jsonParser.getValueAsString();
        int prec = 1;
        if (fmt.prec() != 0) {
            prec = (int) Math.pow(10, fmt.prec());
        }
        return new BigDecimal(num).multiply(new BigDecimal(prec)).setScale(0, BigDecimal.ROUND_HALF_UP).longValue();
    }

    @Override
    public JsonDeserializer<?> createContextual(DeserializationContext deserializationContext, BeanProperty beanProperty) {
        if (beanProperty != null) {
            Class<?> rawClass = beanProperty.getType().getRawClass();
            if (long.class == rawClass || Long.class == rawClass) {
                LongFormat attr = beanProperty.getAnnotation(LongFormat.class);
                if (attr != null) {
                    LongDeserializer deser = new LongDeserializer();
                    deser.fmt = attr;
                    return deser;
                }
            }
        }
        return this;
    }
}
